import { Injectable, OnModuleInit } from '@nestjs/common';
import * as fs from 'node:fs';
import { cityKeys } from '../consts/resource.consts';

@Injectable()
export class WeatherService implements OnModuleInit {
  onModuleInit() {
    const data = fs.readFileSync('resource/citycode.json', 'utf-8');
    var parse = JSON.parse(data);
    Object.assign(cityKeys, parse);
  }

  queryCityName(cityName: string) {
    return cityKeys.find((e) => e.cityName === cityName);
  }

  async query(cityKey: string) {
    let baseApi = ` http://t.weather.sojson.com/api/weather/city/${cityKey}`;
    const res = await fetch(baseApi);
    if (!res.ok) throw new Error(res.statusText);
    return (await res.json())['data'];
  }
}
